<template>
  <el-form :model="form" label-width="auto" style="padding: 20px 20px 0 20px;">
    <el-form-item label="生产单号">
      <el-select v-model="form.productionNo">
        <el-option v-for="(dict, index) in productionList" :key="index" :label="dict.productionNo"
          :value="dict.productionNo" @click="select(index)" />
      </el-select>
    </el-form-item>
    <el-form-item label="生产计划名称">
      <el-input v-model="form.workOrderName" disabled />
    </el-form-item>
    <el-form-item label="退料数量">
      <el-table :data="exitList" border style="width: 100%">
        <el-table-column label="序号" width="55" align="center">
          <template v-slot="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="goodsNo" label="物料编号" min-width="188" align="center" />
        <el-table-column prop="goodsName" label="物料名称" align="center" />
        <el-table-column prop="checkoutNumber" label="领料数量" align="center" />
        <el-table-column label="退料数量" align="center">
          <template v-slot="scope">
            <el-input v-model.number="scope.row.number" placeholder="请输入出库数量" />
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">确认</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { getExitInfo, getExitList, returnMaterial } from '@/api/production/exit'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

let form = ref({})
let productionList = ref([])
let exitList = ref([])

//获取工单列表
function getInfo() {
  getExitInfo().then(response => {
    productionList.value = response.rows
  })
}

//选中生产单号自动出现生产计划名称以及退料表格
function select(index) {
  form.value.workOrderName = productionList.value[index].workOrderName
  getExitList(form.value.productionNo).then(response => {
    for(let i = 0;i < response.rows.length;i++) {
      response.rows[i].number = 0
    }
    exitList.value = response.rows
  })
}

function onSubmit() {
  let inStockForm = ref({
    sourceNo: form.value.productionNo,
    list: []
  })

  for(let i = 0;i < exitList.value.length;i++) {
    if(exitList.value[i].number < 0 || exitList.value[i].number > exitList.value[i].checkoutNumber) {
      ElMessageBox.alert('当前输入的退料数量总数不符合规定,请合理退料', '系统提示', {
        confirmButtonText: '好的',
      })
      return
    }
    if(exitList.value[i].number > 0) {
      inStockForm.value.list.push(exitList.value[i])
    }
  }
  returnMaterial(inStockForm.value).then(response => {
    ElMessage({
      type: 'success',
      message: '退料成功'
    })
    router.push("/production/exit")
  })

}

function cancel() {
  router.push("/production/exit")
}

onMounted(() => {
  getInfo()
})

</script>

<style scoped></style>